package com.itheima.userservice.elasticsearch;

import com.alibaba.fastjson2.JSON;
import com.itheima.userservice.bean.Hotel;
import com.itheima.userservice.config.ElasticSearchConfig;
import com.itheima.userservice.mapper.HotelUseMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class HotelUseServiceImpl implements HotelUseService {

    @Autowired
    private HotelUseMapper mapper;

    @Autowired
    private ElasticSearchConfig client;

    @Override
    public List<Hotel> selectList() {
        //全量同步,查询mysql的数量
        List<Hotel> list = mapper.selectAll();

        BulkRequest request = new BulkRequest();

        if (!list.isEmpty()) {
            list.forEach(hotel -> {
                String s = JSON.toJSONString(hotel);
                request.add(new IndexRequest("hotel").id(String.valueOf(hotel.getId()))
                .source(s, XContentType.JSON));
            });
        }
        try {
            client.restHighLevelClient().bulk(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            System.out.println("全量同步报错了");
        }
        return null;
    }
}
